﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Flags.cs" company="">
//   
// </copyright>
// <summary>
//   Flag集合
// </summary>
// --------------------------------------------------------------------------------------------------------------------

using System.Collections.Generic;

using CxExtension;

/// <summary>
/// Flag集合
/// </summary>
public abstract class Flags : IFlag
{
	private IFlag mBaseFlag = new FlagBool();//基础默认值
	protected readonly List<ICondition> mFlags = new List<ICondition>();

	protected Flags(bool value)
	{
		mBaseFlag.Set(value);
		AddCondition(mBaseFlag);
	}

	public bool BaseValue
	{
		get
		{
			return mBaseFlag.Check();
		}
	}
	/// <summary>
	/// 取得一个bool值的flag
	/// </summary>
	/// <param name="value" />
	/// <returns></returns>
	public FlagBool GetBool(bool value)
	{
		var flag = new FlagBool(value);
		Add(flag);
		return flag;
	}

	/// <summary>
	/// 取得一个用obj做实例的标记
	/// </summary>
	/// <param name="value"></param>
	/// <param name="obj"></param>
	/// <returns></returns>
	public FlagBoolObj GetBoolObj(bool value, object obj)
	{
		var flag = new FlagBoolObj(value, obj);
		Add(flag);
		return flag;
	}

	/// <summary>
	/// 添加一个flag
	/// </summary>
	/// <param name="flag"></param>
	public void Add(Flag flag)
	{
		var add = AddCondition(flag);
		if(add)
		{
			flag.SetParent(this);
		}
	}

	/// <summary>
	/// 添加一个条件
	/// </summary>
	/// <param name="item"></param>
	/// <returns></returns>
	public bool AddCondition(ICondition item)
	{
		if(item == null) return false;
		if(mFlags.Contains(item))
		{
			return false;
		}

		mFlags.Add(item);
		return true;
	}

	public void Remove(ICondition flag)
	{
		mFlags.Remove(flag);
	}

	public void RemoveByObj(object obj)
	{
		for(var i = mFlags.Count - 1; i >= 0; i--)
		{
			var it = mFlags[i];
			if(obj == null) continue;
			var v = it as FlagBoolObj;
			if(v == null) continue;
			if(v.Obj != obj) continue;

			mFlags.Remove(v);
			return;
		}
	}

	public abstract bool Check();

	public static implicit operator bool(Flags value)
	{
		return value != null && value.Check();
	}

	/// <summary>
	/// 设置基础值为true
	/// </summary>
	public void True()
	{
		mBaseFlag.True();
	}

	/// <summary>
	/// 设置基础值为false
	/// </summary>
	public void False()
	{
		mBaseFlag.False();
	}

	/// <summary>
	/// 设置基础值
	/// </summary>
	/// <param name="value"></param>
	public void Set(bool value)
	{
		mBaseFlag.Set(value);
	}
}